package com.doctor.ui;

import java.util.List;

import com.doctor.bean.UserBean;
import com.doctor.bean.UserListBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.FileHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.MyApplication;
import com.doctor.comm.URLConfig;
import com.doctor.database.DES;
import com.doctor.database.DbOperator;
import com.doctor.net.GetDataThread;
import com.doctor.net.NetUtil;
import com.doctor.net.RequestParams;
import com.doctor.ui.medicalknowledge.KnowledgeActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.net.GetDataThread.DataCallback;

public class LoginActivity extends BaseActivity {
	
	private EditText account,passWord;  //帐号、密码
	private Button loginBtn;    //登录按钮
	private long oldTime;
	private TextView remeberPasswordTxt;
	private CheckBox remeberPassword;
	//登录提示progress
	private ProgressBar loginTip;
	//用户的省份、城市、县信息
	private volatile String province, city, county;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		
		initiaView();
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		account.setText("");
		passWord.setText("");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long nowTime= java.lang.System.currentTimeMillis();
			long between = nowTime- oldTime;
			if (between<=2000) {
				DbOperator.getInstance(LoginActivity.this).close();
				LoginActivity.this.finish();
				java.lang.System.exit(0);
			}else {
				oldTime= nowTime;
				Toast.makeText(LoginActivity.this, "再按一次退出医师宝！", 2000).show();
			}
		}
		return true;
	}
	
	
	/**
	 * 检测并设置省份
	 */
	private void checkAndSetProvince() {
		LoadingTip.showDialog(this, "正在加载省份...");
		new Thread() {
			public void run() {
				final List<String> provinces = DbOperator.getInstance(MyApplication.getInstance()).selectProvinces();
				runOnUiThread(new Runnable() {
					public void run() {
						LoadingTip.hideDialog();
						if (provinces == null) {
							LoadingTip.showToast(LoginActivity.this, "没有省份数据！");
							return;
						}
						
						final String[] selectedProvince = {null};  //设置的省份
						AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, R.style.common_dialog);
						builder.setTitle("设置省份");
						builder.setIcon(R.drawable.alert_icon);
						builder.setSingleChoiceItems((provinces.toArray(new String[provinces.size()])), -1, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								selectedProvince[0] = provinces.get(arg1);
							}
						});
						builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								if (selectedProvince[0] != null && selectedProvince[0].trim().length() > 0) {
									ContentValues values = new ContentValues();
									values.put("_province", selectedProvince[0]);
									int rows = DbOperator.getInstance(LoginActivity.this).updateData(ConstConfig.USER_REGION_TABLE, values, 1);
									if (rows == 1) {
										province = selectedProvince[0];
									}
									checkAndSetCity();
								}
							}
						});
						builder.setNegativeButton("取消", null);
						builder.setCancelable(false);
						builder.create().show();
					}
				});
			}
		}.start();
	}
	
	
	/**
	 * 检测并设置城市
	 * @param province 所在的省份
	 */
	private void checkAndSetCity() {
		LoadingTip.showDialog(this, "正在加载城市...");
		new Thread() {
			public void run() {
				final List<String> cities = DbOperator.getInstance(MyApplication.getInstance()).selectCities(province);
				runOnUiThread(new Runnable() {
					public void run() {
						LoadingTip.hideDialog();
						if (cities == null) {
							LoadingTip.showToast(LoginActivity.this, "没有城市数据！");
							return;
						}
						
						final String[] selectedCity = {null};  //设置的城市
						AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
						builder.setTitle("设置城市");
						builder.setIcon(R.drawable.alert_icon);
						builder.setSingleChoiceItems((cities.toArray(new String[cities.size()])), -1, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								selectedCity[0] = cities.get(arg1);
							}
						});
						builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								if (selectedCity[0] != null && selectedCity[0].trim().length() > 0) {
									ContentValues values = new ContentValues();
									values.put("_city", selectedCity[0]);
									int rows = DbOperator.getInstance(LoginActivity.this).updateData(ConstConfig.USER_REGION_TABLE, values, 1);
									if (rows == 1) {
										city = selectedCity[0];
									}
									checkAndSetCounty();
								}
							}
						});
						builder.setNegativeButton("取消", null);
						builder.setCancelable(false);
						builder.create().show();
					}
				});
			}
		}.start();
	}
	
	
	/**
	 * 检测并设置城市
	 * @param province 所在的省份
	 */
	private void checkAndSetCounty() {
		LoadingTip.showDialog(this, "正在加载县...");
		new Thread() {
			public void run() {
				final List<String> counties = DbOperator.getInstance(MyApplication.getInstance()).selectCounty(province, city);
				runOnUiThread(new Runnable() {
					public void run() {
						LoadingTip.hideDialog();
						if (counties == null) {
							LoadingTip.showToast(LoginActivity.this, "没有县数据！");
							return;
						}
						
						final String[] selectedCounty = {null};  //选择的县
						AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
						builder.setTitle("设置县");
						builder.setIcon(R.drawable.alert_icon);
						builder.setSingleChoiceItems((counties.toArray(new String[counties.size()])), -1, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								selectedCounty[0] = counties.get(arg1);
							}
						});
						builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								if (selectedCounty[0] != null && selectedCounty[0].trim().length() > 0) {
									ContentValues values = new ContentValues();
									values.put("_county", selectedCounty[0]);
									int rows = DbOperator.getInstance(LoginActivity.this).updateData(ConstConfig.USER_REGION_TABLE, values, 1);
									if (rows == 1) {
										county = selectedCounty[0];
									}
								}
							}
						});
						builder.setNegativeButton("取消", null);
						builder.setCancelable(false);
						builder.create().show();
					}
				});
			}
		}.start();
	}
	
	
	@Override
	protected void initiaView() {
		remeberPassword=(CheckBox) findViewById(R.id.remeberPassword);
		remeberPasswordTxt=(TextView) findViewById(R.id.remeberPasswordTxt);
		remeberPasswordTxt.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				remeberPassword.setChecked(remeberPassword.isChecked()?false:true);
			}
		});
		
		account=(EditText) findViewById(R.id.account);
		passWord=(EditText) findViewById(R.id.password);
		
		SharedPreferences loginSetting=getSharedPreferences(ConstConfig.LOGIN_SETTING, Activity.MODE_PRIVATE);
		boolean isRememberPassword=loginSetting.getBoolean("password", true);
		if (isRememberPassword) {
			remeberPassword.setChecked(true);
		}
		
		List<String> loginInfo=DbOperator.getInstance(LoginActivity.this).selectLoginInfo();
		if (loginInfo.size()>0) {
			String account_txt = loginInfo.get(1);
			if (account_txt != null && account_txt.length() > 0) {
				//显示帐号并设置其不可编辑
				account.setText(loginInfo.get(1));
				account.setEnabled(false);
			}
			
			if (isRememberPassword) {
				passWord.setText(loginInfo.get(2));
			}
		}
		
		String[] region = DbOperator.getInstance(LoginActivity.this).selectUserRegion();
		if (region != null) {
			province = region[0] != null && region[0].trim().length() > 0 ? region[0] : null;
			city = region[1] != null && region[1].trim().length() > 0 ? region[1] : null;
			county = region[2] != null && region[2].trim().length() > 0 ? region[2] : null;
		}
		
		View view=findViewById(R.id.login_bg);
		loginTip=(ProgressBar) findViewById(R.id.loginTip);
		loginBtn=(Button) findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (province == null || province.trim().length() <= 0) {
					checkAndSetProvince();
					return;
				} else if (city == null || city.trim().length() <= 0) {
					checkAndSetCity();
					return;
				} else if (county == null || county.trim().length() <= 0) {
					checkAndSetCounty();
					return;
				}
				
				String account_txt=account.getText().toString();
				String passWord_txt=passWord.getText().toString();
				if (account_txt==null || account_txt.length()<=0) {
					Toast.makeText(LoginActivity.this, "请输入帐号！", Toast.LENGTH_SHORT).show();
				} else if (passWord_txt==null || passWord_txt.length()<=0) {
					Toast.makeText(LoginActivity.this, "请输入密码！", Toast.LENGTH_SHORT).show();
				} else {
					goToKnowledgeActivity(account_txt, passWord_txt);
				}
			}
		});
		
//		AlphaAnimation animation=new AlphaAnimation(0f, 1f);
//		animation.setDuration(2000);  //动画设置2秒		
//		view.startAnimation(animation);
//		animation.setAnimationListener(new Animation.AnimationListener(){
//
//			@Override
//			public void onAnimationEnd(Animation animation) {
//				// TODO Auto-generated method stub
//				if (province == null || province.trim().length() <= 0) {
//					checkAndSetProvince();
//				} else if (city == null || city.trim().length() <= 0) {
//					checkAndSetCity();
//				}
//			}
//
//			@Override
//			public void onAnimationRepeat(Animation animation) {
//				// TODO Auto-generated method stub
//				
//			}
//
//			@Override
//			public void onAnimationStart(Animation animation) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//		});
		if (province == null || province.trim().length() <= 0) {
			checkAndSetProvince();
		} else if (city == null || city.trim().length() <= 0) {
			checkAndSetCity();
		} else if (county == null || county.trim().length() <= 0) {
			checkAndSetCounty();
		}
	}
	
	
	/**
	 * 跳转至医疗技术页面
	 * @param account 帐号
	 * @param passWord 密码
	 */
	private void goToKnowledgeActivity(final String account, final String passWord){
		//loginBtn设为false防止一次请求多次登录
		loginBtn.setEnabled(false);
		loginTip.setVisibility(View.VISIBLE);
		
		final String deviceId = FileHelper.getImieStatus(this);		
		//本地数据库的用户信息
		final UserBean bean=DbOperator.getInstance(LoginActivity.this).selectUserInfo();
		
		if (NetUtil.hasNetwork(LoginActivity.this)) {
			//有网络连接的情况
			RequestParams params=new RequestParams(URLConfig.LOGIN_URL+account+"&pwd="+passWord+"&serial_number="+deviceId,
					LoginActivity.this, null, UserListBean.class);
			
			GetDataThread.getInstance(LoginActivity.this).getDataFromServer(ConstConfig.POST, params, new DataCallback<UserListBean>() {
				@Override
				public void processData(UserListBean paramObject,boolean paramBoolean) {
					// TODO Auto-generated method stub
					
					loginBtn.setEnabled(true);
					loginTip.setVisibility(View.INVISIBLE);
					
					//// TODO: 2017/3/11 这里设置是否进入
					if (paramObject==null || paramObject.getSize()<=0) {
						Toast.makeText(LoginActivity.this, "验证失败，请输入正确的密码！", Toast.LENGTH_SHORT).show();
						return;
					}
					UserBean bean1=paramObject.getDataList().get(0);
					ContentValues values=new ContentValues();
					
					if (bean==null) {
						try {
							//重要信息进行加密
							String encryptedId=DES.encryptDES(bean1.getId()+"", DES.KEY);
							String encryptedUsername=DES.encryptDES(bean1.getUsername()+"", DES.KEY);
							String encryptedMm=DES.encryptDES(bean1.getMm()+"", DES.KEY);
							String encryptedSerial=DES.encryptDES(deviceId, DES.KEY);
							
							values.put("_id", encryptedId);
							values.put("_username", encryptedUsername);
							values.put("_serial", encryptedSerial);						
							values.put("_mm", encryptedMm);
//							values.put("_realname", bean1.getRealname());
//							values.put("_sex", bean1.getSex());
//							values.put("_mobile", bean1.getMobile());
//							values.put("_dwname", bean1.getDwname());
//							values.put("_cs", bean1.getCs());
//							values.put("_state", bean1.getState());
//							values.put("_addtime", bean1.getAddtime());
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						long row=DbOperator.getInstance(LoginActivity.this).insertData(ConstConfig.USER_TABLE, values);
						if (row>0) {
							final Intent intent=new Intent(LoginActivity.this, KnowledgeActivity.class);
							startActivity(intent);
							//放置在内存当中的用户信息
							UserBean cacheUser = new UserBean();
							cacheUser.setId(bean1.getId());
							cacheUser.setUsername(bean1.getUsername());
							cacheUser.setMm(bean1.getMm());
							cacheUser.setSerial_number(deviceId);
							MyApplication.getInstance().setUserBean(cacheUser);
							saveLoginSetting();
							finish();
						}
					} else {
						if (!account.equals(bean.getUsername()) || !deviceId.equals(bean.getSerial_number())) {
							Toast.makeText(LoginActivity.this, "请输入正确的密码！", Toast.LENGTH_SHORT).show();
							return;
						}
						//对比密码，密码不一致则更新密码
						boolean isUpdated=true;
						if(!bean.getMm().equals(bean1.getMm())){
							values.clear();
							String encryptedMm = null;
							String encryptedId = null;
							try {
								encryptedMm=DES.encryptDES(bean1.getMm()+"", DES.KEY);
								encryptedId=DES.encryptDES(bean.getId()+"", DES.KEY);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							values.put("_mm", encryptedMm);	
							int rows=DbOperator.getInstance(LoginActivity.this).updateData(ConstConfig.USER_TABLE, values, encryptedId);
							isUpdated=(rows>0?true:false);
						}
						if (isUpdated) {
							final Intent intent=new Intent(LoginActivity.this, KnowledgeActivity.class);
							startActivity(intent);
							bean.setMm(bean1.getMm());
							MyApplication.getInstance().setUserBean(bean);
							saveLoginSetting();
							finish();
						}
					}
				}
			});	
		} else {
			
			loginBtn.setEnabled(true);
			loginTip.setVisibility(View.INVISIBLE);
			//没有网络连接
			if (bean==null) {
				Toast.makeText(LoginActivity.this, "第一次登录验证请连接网络！", Toast.LENGTH_SHORT).show();
				return;
			}
			if (account.equals(bean.getUsername()) && passWord.equals(bean.getMm()) && deviceId.equals(bean.getSerial_number())) {
				final Intent intent=new Intent(LoginActivity.this, KnowledgeActivity.class);
				startActivity(intent);
				MyApplication.getInstance().setUserBean(bean);
				saveLoginSetting();
				finish();
			} else {
				Toast.makeText(LoginActivity.this, "请输入正确的密码！", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		
	}
	
	/**
	 * 保存登录的设置信息
	 */
	private void saveLoginSetting(){
		SharedPreferences loginSetting=getSharedPreferences(ConstConfig.LOGIN_SETTING, Activity.MODE_PRIVATE);
		Editor editor=loginSetting.edit();
		editor.putBoolean("password", remeberPassword.isChecked()?true:false);
		editor.apply();
	}
	
}
